import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: 'http://101.35.110.199:8000',
  timeout: 60000  // 增加到60秒，因为路线生成可能需要较长时间
})

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理错误
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

// 用户认证相关API
export const authAPI = {
  // 用户注册
  register: (data: { username: string; password: string }) => {
    return api.post('/register', data)
  },
  
  // 用户登录
  login: (data: { username: string; password: string }) => {
    return api.post('/login', data)
  }
}

// 路线生成相关API
export const routeAPI = {
  // 生成旅游路线
  generateRoute: (data: {
    destination: string
    days: number
    budget: 'low' | 'medium' | 'high'
    people: number
  }) => {
    return api.post('/api/generate-route', data)
  },
  
  // 验证路线
  validateRoute: (data: {
    days: Array<{
      day: number
      attractions: string[]
      hotel: string
      total_drive_time: number
    }>
    destination: string
  }) => {
    return api.post('/api/validate-route', data)
  },
  
  // 获取格式化的路线
  getFormattedRoute: (routeId: number) => {
    return api.get(`/api/routes/${routeId}/formatted`)
  }
}

export default api 